const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const fileUpload = require('express-fileupload');
require('dotenv').config();

const app = express();
// 获取局域网 IP 地址，固定端口为 5201
const host = '192.168.1.150';  // 或者直接设置为你的局域网 IP
const port = 5201;        // 固定端口为 5201

const videoDir = path.join(__dirname, 'videos');
const thumbnailDir = path.join(__dirname, 'thumbnails');
const avatarDir = path.join(__dirname, 'avatars'); // 新增头像目录
const usersFile = path.join(__dirname, 'users.json');
const videosFile = path.join(__dirname, 'videos.json'); // 新增视频存储文件

// 创建必要的目录
if (!fs.existsSync(avatarDir)) {
    fs.mkdirSync(avatarDir);
}
if (!fs.existsSync(videosFile)) {
    fs.writeFileSync(videosFile, '[]'); // 初始化空的JSON文件
}

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname)));
app.use(fileUpload());

// Nodemailer配置
const transporter = nodemailer.createTransport({
    service: 'QQ',
    auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS
    }
});

let verificationCodes = {}; // 存储验证码

// 生成随机验证码
function generateCode() {
    return crypto.randomInt(100000, 999999).toString();
}

// 提供视频文件列表
app.get('/videos', (req, res) => {
    const videos = JSON.parse(fs.readFileSync(videosFile, 'utf8'));
    res.status(200).json(videos);
});

// 注册用户
app.post('/register', (req, res) => {
    const { email, password, code } = req.body;

    // 验证验证码
    if (verificationCodes[email] !== code) {
        return res.status(400).json({ message: '验证码错误' });
    }

    // 加密密码
    const hashedPassword = bcrypt.hashSync(password, 8);

    // 读取现有用户数据
    let users = JSON.parse(fs.readFileSync(usersFile));

    // 检查用户是否已存在
    if (users.find(user => user.email === email)) {
        return res.status(400).json({ message: '用户已存在' });
    }

    // 添加新用户
    users.push({
        email,
        password: hashedPassword,
        avatar: '/avatars/default-avatar.png', // 使用默认头像
        name: '',
        experience: 0,
        lastSignIn: ''
    });
    fs.writeFileSync(usersFile, JSON.stringify(users));

    // 清除验证码
    delete verificationCodes[email];

    res.status(200).json({ message: '注册成功' });
});

// 登录用户
app.post('/login', (req, res) => {
    const { email, password } = req.body;

    // 读取现有用户数据
    let users = JSON.parse(fs.readFileSync(usersFile));

    // 查找用户
    const user = users.find(user => user.email === email);
    if (!user) {
        return res.status(400).json({ message: '用户不存在' });
    }

    // 验证密码
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
        return res.status(401).json({ message: '密码错误' });
    }

    // 创建和发送JWT
    const token = jwt.sign({ email: user.email }, 'your-secret-key', { expiresIn: '1h' });
    res.status(200).json({ auth: true, token, user });
});

// 获取用户信息
app.get('/user', (req, res) => {
    const token = req.headers['x-access-token'];
    if (!token) return res.status(401).json({ message: '没有提供token' });

    jwt.verify(token, 'your-secret-key', (err, decoded) => {
        if (err) return res.status(500).json({ message: 'token验证失败' });

        let users = JSON.parse(fs.readFileSync(usersFile));
        const user = users.find(user => user.email === decoded.email);
        if (!user) return res.status(404).json({ message: '用户未找到' });

        res.status(200).json({ user });
    });
});

// 更新用户信息
app.post('/update-user', (req, res) => {
    const token = req.headers['x-access-token'];
    if (!token) return res.status(401).json({ message: '没有提供token' });

    jwt.verify(token, 'your-secret-key', (err, decoded) => {
        if (err) return res.status(500).json({ message: 'token验证失败' });

        let users = JSON.parse(fs.readFileSync(usersFile));
        let userIndex = users.findIndex(user => user.email === decoded.email);
        if (userIndex === -1) return res.status(404).json({ message: '用户未找到' });

        const name = req.body.name;
        if (name) users[userIndex].name = name;

        if (req.files && req.files.avatar) {
            const avatar = req.files.avatar;
            const avatarName = `${decoded.email}-${Date.now()}-${avatar.name}`;
            const avatarPath = path.join(avatarDir, avatarName);

            // 保存上传的文件到指定路径
            avatar.mv(avatarPath, (err) => {
                if (err) return res.status(500).json({ message: '头像上传失败' });
            });

            // 将头像的相对路径保存到用户数据中
            users[userIndex].avatar = `/avatars/${avatarName}`;
        }

        fs.writeFileSync(usersFile, JSON.stringify(users));
        res.status(200).json({ message: '用户信息更新成功' });
    });
});

// 签到
app.post('/sign-in', (req, res) => {
    const token = req.headers['x-access-token'];
    if (!token) return res.status(401).json({ message: '没有提供token' });

    jwt.verify(token, 'your-secret-key', (err, decoded) => {
        if (err) return res.status(500).json({ message: 'token验证失败' });

        let users = JSON.parse(fs.readFileSync(usersFile));
        let userIndex = users.findIndex(user => user.email === decoded.email);
        if (userIndex === -1) return res.status(404).json({ message: '用户未找到' });

        const today = new Date().toLocaleDateString();
        if (users[userIndex].lastSignIn !== today) {
            users[userIndex].experience += 10;
            users[userIndex].lastSignIn = today;
            fs.writeFileSync(usersFile, JSON.stringify(users));
            return res.status(200).json({ message: '签到成功', experience: users[userIndex].experience });
        } else {
            return res.status(400).json({ message: '今天已经签到过了' });
        }
    });
});

// 上传视频和缩略图
app.post('/upload', (req, res) => {
    const { videoTitle, videoCategory } = req.body; // 接收视频标题和分类
    const token = req.headers['x-access-token'];
    if (!token) return res.status(401).json({ message: '没有提供token' });

    jwt.verify(token, 'your-secret-key', (err, decoded) => {
        if (err) return res.status(500).json({ message: 'token验证失败' });

        let videos = JSON.parse(fs.readFileSync(videosFile));
        if (!req.files || !req.files.video || !req.files.thumbnail) {
            return res.status(400).json({ message: '没有上传文件' });
        }

        const video = req.files.video;
        const thumbnail = req.files.thumbnail;

        const videoId = Date.now(); // 使用当前时间戳生成唯一的视频编号
        const videoPath = path.join(videoDir, videoId + path.extname(video.name)); // 保存视频编号
        const thumbnailPath = path.join(thumbnailDir, videoId + path.extname(thumbnail.name)); // 保存缩略图

        video.mv(videoPath, (err) => {
            if (err) return res.status(500).json({ message: '上传视频失败' });

            thumbnail.mv(thumbnailPath, (err) => {
                if (err) return res.status(500).json({ message: '上传缩略图失败' });

                // 记录视频信息
                const newVideo = {
                    id: videoId,
                    title: videoTitle,
                    category: videoCategory, // 视频分类
                    videoPath: `/videos/${videoId}${path.extname(video.name)}`,
                    thumbnailPath: `/thumbnails/${videoId}${path.extname(thumbnail.name)}`,
                    uploader: decoded.email,
                    uploadDate: new Date().toISOString(),
                    views: 0 // 初始播放量为0
                };

                videos.push(newVideo);
                fs.writeFileSync(videosFile, JSON.stringify(videos));

                res.status(200).json({ message: '上传成功', video: newVideo });
            });
        });
    });
});

// 获取视频详情（包括编号、分类、发布人、播放量等）
app.get('/video/:id', (req, res) => {
    const videoId = parseInt(req.params.id);
    let videos = JSON.parse(fs.readFileSync(videosFile));
    const video = videos.find(v => v.id === videoId);

    if (!video) return res.status(404).json({ message: '视频未找到' });

    // 更新播放量
    video.views += 1;
    fs.writeFileSync(videosFile, JSON.stringify(videos));

    res.status(200).json(video);
});

// 发送验证码
app.post('/send-code', (req, res) => {
    const { email } = req.body;

    // 生成验证码
    const code = generateCode();
    verificationCodes[email] = code;

    // 发送邮件
    const mailOptions = {
        from: process.env.EMAIL_USER,
        to: email,
        subject: '注册验证码',
        text: `您的验证码是：${code},最好不要告诉别人(OvO)`
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(500).json({ message: '无法发送邮件' });
        }
        res.status(200).json({ message: '验证码已发送' });
    });
});

app.listen(port, host, () => {
  console.log(`服务器端口为 http://${host}:${port}/`);
});
